package cn.yougou.serviceImpl;

import cn.yougou.common.AnalysisFileUtil;
import cn.yougou.common.VoDataUtil;
import cn.yougou.mapper.YgCommodityMapper;
import cn.yougou.mapper.YgOrderMapper;
import cn.yougou.mapper.YgUserCouponsMapper;
import cn.yougou.pojo.YgCommodity;
import cn.yougou.pojo.YgCoupons;
import cn.yougou.pojo.YgOrder;
import cn.yougou.pojo.YgUserCoupons;
import cn.yougou.service.YgCouponRules;
import cn.yougou.service.YgUserCouponsService;
import cn.yougou.service.shopcart.YgCommodityService;
import cn.yougou.service.shopcart.YgCouponsService;
import cn.yougou.vo.*;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: DELL
 * @date: 2021/1/1 19:36
 * @description:
 */
@Service
public class YgUserCouponServiceImpl implements YgUserCouponsService {
    @Autowired
    private YgOrderMapper ygOrderMapper;
    @Autowired
    YgUserCouponsMapper ygUserCouponsMapper;
    @Autowired
    YgCouponsService ygCouponsService;
    @Autowired
    VoDataUtil voDataUtil;
    @Autowired
    YgCommodityService ygCommodityService;
    @Autowired
     AnalysisFileUtil analysisFileUtil;
    @Autowired
    YgCouponRules ygCouponRules;
    @Autowired
    YgCommodityMapper ygCommodityMapper;
    @Override
    public Integer queryCouponCount(YgUserCoupons ygUserCoupons) {
        return ygUserCouponsMapper.queryCouponCount(ygUserCoupons);
    }

    @Override
    public YgUserCoupons queryById(Object id) {
        return ygUserCouponsMapper.queryById(id);
    }

    @Override
    public List<YgUserCoupons> queryAllByLimit(int offset, int limit) {
        return ygUserCouponsMapper.queryAllByLimit(offset,limit);
    }

    @Override
    public Integer insert(YgUserCoupons ygUserCoupons) {
        return ygUserCouponsMapper.insert(ygUserCoupons);
    }

    @Override
    public Integer update(YgUserCoupons ygUserCoupons) {
        return ygUserCouponsMapper.update(ygUserCoupons);
    }

    @Override
    public Integer deleteById(Object id) {
        return ygUserCouponsMapper.deleteById(id);
    }

    @Override
    public List<YgGetCouponListVo> getUserCouponList(Integer userId, YgResOrderVo ygResOrderVo) {

        //可以使用的优惠券
        List<YgUserCoupons> qualified =new ArrayList<> ();
        //不能使用的优惠券
        List<YgUserCoupons> disqualification =new ArrayList<> ();
        //从数据库中查询出用户的优惠券信息
        List<YgUserCoupons> userCouponList = ygUserCouponsMapper.getUserCouponList(userId);
        //将列表按照优惠券id区分 存入map
        Map<String,List<YgUserCoupons>> groupByYgUserCouponsList = getGroupByYgUserCouponsList(userCouponList);
        //按照 优惠券id 将对应的 类型范围 商品范围 禁用范围查出
        List<YgCoupons> Scope = getCouponsScope(groupByYgUserCouponsList);
        //根据传来的商品id 查出对应的 类型id
        List<YgCommodity> commodityList = getComodityList(ygResOrderVo.getYgResCommodityVos());
        //开始判断 将满足条件的优惠券 存入可以使用list 将不满足的优惠券存入不能使用的list
        differentiateList(ygResOrderVo.getYgResCommodityVos(),groupByYgUserCouponsList,Scope,commodityList,qualified,disqualification);

        // 对 可用list 进行优惠力度的判断 将优惠力度大的排在前面
        for(int i =0;i<qualified.size();i++){
            YgCouponDerateResultVo derateResult = ygCouponRules.getDerateResult(qualified.get(i), ygResOrderVo);
            if(derateResult!=null){
                qualified.get(i).setDerateResultMoney(derateResult.getDerate());
            }else{
                disqualification.add(qualified.get(i));
                qualified.remove(i);
            }

        }
        YgUserCoupons middle =null;
        for(int i =0;i< qualified.size()-1;i++){
            for(int a =0;a<qualified.size()-1-i; a++){
                //判断
                double value1 =qualified.get(a).getDerateResultMoney();
                double value2 =qualified.get(a+1).getDerateResultMoney();
                if(value1<value2){
                    middle =qualified.get(a+1);//将第二个值存到中间值
                    qualified.set(a+1,qualified.get(a));
                    qualified.set(a,middle);
                }
            }
        }

        //然后将排序后的list返回
        //整理 qualified 和 disqualification 将他们组成一个
        List list = disposeReturnList(voDataUtil.YgGetCouponListVoUserCoupons(qualified, 1), voDataUtil.YgGetCouponListVoUserCoupons(disqualification, 0));
       /* for (int i = 0; i <list.size();i++ ){
            System.out.println(list.get(i).toString());
        }*/
        return  list;

    }
    //计算实际价格 与 优惠价格
    @Override
    public YgResOrderVo calculateMoney(YgResOrderVo ygResOrderVo) {
       //循环遍历出商品的总价格
        double count = 0.0;
        double DerateResultMoney =0.0;
        count = calculateCountMoney(ygResOrderVo.getYgResCommodityVos());
      /*  for (int i = 0; i < ygResOrderVo.getYgResCommodityVos().length; i++){
            System.out.println(ygResOrderVo.getYgResCommodityVos()[i]);
        }*/
        //计算出实际优惠价格
        try {

                YgUserCoupons ygUserCoupons = ygUserCouponsMapper.queryById(ygResOrderVo.getCouponsid());
                YgCouponDerateResultVo derateResult = ygCouponRules.getDerateResult(ygUserCoupons, ygResOrderVo);
                DerateResultMoney =derateResult.getDerate();
            //System.out.println(derateResult.getOrderDate());
        }catch (Exception e) {
            e.printStackTrace();
            count = 0.0;
            DerateResultMoney =0.0;
        }

        //整理返回
        return new YgResOrderVo((count-DerateResultMoney>0)? DerateResultMoney:count,(count-DerateResultMoney>0)?count-DerateResultMoney:0,count);
    }
    @Override
    public YgResOrderVo calculateMoneyH(YgResOrderVo ygResOrderVo) {
        //循环遍历出商品的总价格
        double count = 0.0;
        double DerateResultMoney =0.0;
        YgResCommodityVo[] ygResCommodityVos = ygResOrderVo.getYgResCommodityVos();

        count = calculateCountMoney(ygResOrderVo.getYgResCommodityVos());
        //计算出实际优惠价格
        YgCouponDerateResultVo derateResult =null;
        try {

            YgUserCoupons ygUserCoupons = ygUserCouponsMapper.queryById(ygResOrderVo.getCouponsid());
             derateResult = ygCouponRules.getDerateResult(ygUserCoupons, ygResOrderVo);
           System.out.println(derateResult == null);
            DerateResultMoney =derateResult.getDerate();

        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        if(derateResult!=null){
            //整理返回
            System.out.println(derateResult.getOrderDate());
            return new YgResOrderVo((count-DerateResultMoney>0)? DerateResultMoney:count,(count-DerateResultMoney>0)?count-DerateResultMoney:0,count,derateResult.getOrderDate());

        }else {
            return null;
        }
          }
    /**
     * 遍历YgResCommodityVo 计算出总价格
     * */
    private double calculateCountMoney(YgResCommodityVo [] ygResCommodityVos){
        double count =0.0;
        if(ygResCommodityVos!=null){
            for(int i =0;i<ygResCommodityVos.length;i++){
                count+=ygResCommodityVos[i].getCommodityCount()*ygResCommodityVos[i].getCommodityDouble();
            }
        }
        return count;
    }


    private List<YgGetCouponListVo> disposeReturnList( List<YgGetCouponListVo> qualified,List<YgGetCouponListVo> disqualification){
        //返回list
        List<YgGetCouponListVo> returnList = new ArrayList<> ();
        for(YgGetCouponListVo item:qualified){
            returnList.add(item);
        }
        for(YgGetCouponListVo item:disqualification){
            returnList.add(item);
        }
       return returnList;
    }
    /**
     * //开始判断 将满足条件的优惠券 存入可以使用list 将不满足的优惠券存入不能使用的list
     * */
    public void differentiateList(YgResCommodityVo[] ygResCommodityVos,Map<String,List<YgUserCoupons>> groupByYgUserCouponsList,List<YgCoupons> scope, List<YgCommodity> commodityList, List<YgUserCoupons> qualified, List<YgUserCoupons> disqualification) {
            //开始判断
        if(scope!=null&&commodityList!=null&&qualified!=null&&disqualification!=null&&ygResCommodityVos!=null&&groupByYgUserCouponsList!=null){
            //定义 只要有一件商品可以使用优惠券那么该优惠券就可用
            //根据用户所拥有的优惠券来进行遍历
            for(int i =0;i< scope.size();i++){
                boolean NoOk = true;
                //需要执行哪些判断： 是否处于 禁止使用范围
                // 商品是否在 商品使用范围 若不在则判断是否处于商品类型使用范围
                //如果 不在 禁用范围而且处于优惠券使用范围则添加至 qualified
                for(int a=0;a<ygResCommodityVos.length;a++){
                    //判断禁用范围
                   boolean flag= ygCouponsService.forbidScopeJudge(scope.get(i),ygResCommodityVos[a].getId());
                    if(!flag){
                        //不在禁用范围进行下一次判断
                        //判断是否在商品使用范围 和类型使用范围 如果有一个在 就说明该优惠券可用
                        List<String> typeId = analysisFileUtil.getFileAssignLineList(scope.get(i).getTypeid(), 0);
                        List<String> commodityId = analysisFileUtil.getFileAssignLineList(scope.get(i).getCommodityid(), 0);
                       if(judgeScope(commodityId,(returnYgCommodity(commodityList,ygResCommodityVos[a].getId())==null?null:returnYgCommodity(commodityList,ygResCommodityVos[a].getId()).getId()))||
                               judgeScope(typeId,(returnYgCommodity(commodityList,ygResCommodityVos[a].getId())==null?null:returnYgCommodity(commodityList,ygResCommodityVos[a].getId()).getCategoryid())) ){
                           NoOk=false;
                           setListValue(groupByYgUserCouponsList,qualified,scope.get(i).getId().toString());
                       break;
                       }
                    }
                }
                if(NoOk){
                    setListValue(groupByYgUserCouponsList,disqualification,scope.get(i).getId().toString());
                }
                NoOk =true;
            }
        }
    }
    /**
     * 遍历list 根据传入id返回值
     * **/
    private YgCommodity returnYgCommodity(List<YgCommodity> data ,Integer id){
     if(data!=null){
         for(YgCommodity item: data){
             if(item.getId().toString().equals(id.toString())){
                 return item;
             }
         }
     }
        return null;
    }
    /***
     * 判断list是否包含 value
     * */
    private boolean judgeScope(List<String> data,Integer value){
        if(data!=null&&value!=null){

            for(String item : data){

                if(item.equals(value.toString())){
                    return true;
                }
            }
            return false;
        }
        return false;
    }
    /**
     * 数据添加
     * */
    private void setListValue(Map<String,List<YgUserCoupons>> groupByYgUserCouponsList, List<YgUserCoupons> list,String key){
       List<YgUserCoupons> data = groupByYgUserCouponsList.get(key);
       for(int i=0;i<data.size();i++){
           list.add(data.get(i));
       }
    }
    /**
     * 根据商品idlist查出对应的商品列表
     * */
    public List<YgCommodity> getComodityList(YgResCommodityVo[] ygResCommodityVos) {
        List<YgCommodity> comodityList = null;
        if(ygResCommodityVos!=null&&ygResCommodityVos[0]!=null){
            //先将 【】 变成list
            List idList =new ArrayList();
            for(int i =0;i<ygResCommodityVos.length;i++){
                idList.add(ygResCommodityVos[i].getId());
            }
            List<YgCommodity> ygCommodities = ygCommodityService.queryAllById(idList);
           if(ygCommodities!=null){
               comodityList=ygCommodities;
           }

        }
        return comodityList;
    }

    /**
 * 按照 优惠券id 将对应的 类型范围 商品范围 禁用范围查出
 * */
    public List<YgCoupons> getCouponsScope(Map<String,List<YgUserCoupons>> groupByYgUserCouponsList) {
        List<YgCoupons> scope = null;
        if(groupByYgUserCouponsList!=null){
            List idList = new ArrayList();
            for (Map.Entry<String,List<YgUserCoupons>> entry :groupByYgUserCouponsList.entrySet()) {
                idList.add(entry.getKey());
            }
            //对groupByYgUserCouponsList遍历 将对应key的scope查出
            scope = ygCouponsService.queryAllById(idList);
        }
        return scope;
    }

    /**
 * 将列表按照优惠券id区分 存入map
 * */
    public Map getGroupByYgUserCouponsList( List<YgUserCoupons> userCouponList){
        Map<String,List<YgUserCoupons>> map = null;
        if(userCouponList!=null){
            map =new HashMap();
            for(int i =0;i<userCouponList.size();i++){
                //存在返回true  在现有的list基础上新增
                if(map.containsKey(userCouponList.get(i).getCouponsid().toString())){
                 map.get(userCouponList.get(i).getCouponsid().toString()).add(userCouponList.get(i));
                }else{//不存在 false 创建一个list并存入对象
                    List<YgUserCoupons> list = new ArrayList<>();
                    list.add(userCouponList.get(i));
                    map.put(userCouponList.get(i).getCouponsid().toString(),list);
                }
            }
        }
        return map;
    }
    @Override
    public YgResOrderVo getOrderYgResOrderVo(YgPaymentVo ygPaymentVo) {
        //得到创建账单的数据
        List<YgOrder> commodityData = new ArrayList<> ();
        for(Integer orderId : ygPaymentVo.getOrderIdArr()){
            commodityData.add(ygOrderMapper.queryById(orderId));
        }

        //得到一个优惠券
      //  YgUserCoupons coupon =  queryById(ygPaymentVo.getCouponsId());
        //获取商品列表
        YgResCommodityVo[] ygResCommodityVo = getYgResCommodityVo( commodityData);
        for(int i =0;i< ygResCommodityVo.length;i++){

            for(int a =0;a<commodityData.size();a++){
                if( ygResCommodityVo[i].getId().toString().equals(commodityData.get(a).getCommodityid().toString())){
                    ygResCommodityVo[i].setOrdersn(commodityData.get(a).getOrdersn());
                }
            }
        }
        YgResOrderVo ygResOrderVo = new YgResOrderVo(ygPaymentVo.getUserId(),ygResCommodityVo,ygPaymentVo.getCouponsId());

        YgResOrderVo ygResOrderVo1 = calculateMoneyH(ygResOrderVo);

        return ygResOrderVo1;
    }
    /**
     * 遍历commodityData 获得ygResCommodityVo
     * */
    private YgResCommodityVo[] getYgResCommodityVo(List<YgOrder> commodityData) {
        YgResCommodityVo[] ygResCommodityVo = null;
        if(!commodityData.isEmpty()){
            ygResCommodityVo = new  YgResCommodityVo[commodityData.size()];
            for(int i = 0; i < ygResCommodityVo.length; i++){
                YgCommodity ygCommodity = ygCommodityMapper.queryById(commodityData.get(i).getCommodityid());
                 ygResCommodityVo[i]=new YgResCommodityVo(commodityData.get(i).getCommodityid(),//商品id
                        ygCommodity.getCommodityid(),//商品名称
                        commodityData.get(i).getProductid(),//规格id
                        commodityData.get(i).getPurchseq(),//商品数量
                        commodityData.get(i).getGoodsprice(),//商品单价
                        commodityData.get(i).getPurchsetype()//商品规格描述
                );
            }
        }
        return ygResCommodityVo;
    }
}
